import React, { useState, useMemo, useEffect } from 'react';
import { obj_str, filter_list, is_empty, HandView, ColView, Btn, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, BtTxt,
     stock_log, uDb, uJob, cline, InfoDlg, no_del, PanelFind, loc } from 'sui';
import { get_col, add_pick, load_custom, load_col, get_ck } from './cmd';
import { useAccess } from 'cache';
import { load_supply } from 'stock/base/cmd';
import { Census } from './census';
import { DlgVal, DlgBuy } from './ctl';

const TaskView = () => {
    const [open_val, openVal] = useState(false);
    const [open_info, openInfo] = useState(false);
    const [open_buy, openBuy] = useState(false);
    const [supply, setSupply] = useState();
    const [map_supply, mapSupply] = useState();
    const [custom, setCustom] = useState();
    const [map_custom, mapCustom] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd("oil/list");
    const [no_acc] = useAccess();

    useEffect(() => {
        load_supply("oil", setSupply, mapSupply);
        load_custom(setCustom, mapCustom);
        load_col(setCol);
    }, []);

    const getRow = useMemo(() => {
        const lst = filter_list(["sn"], col);
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter, col]);

    const pact = {
        "pick": v => openVal(true),
        "del": (v) => {
            if (no_del()) {
                return;
            }
            umd.update("oil/rm", { k: obj_str(v, "sn") });

            stock_log("lgoil", v.sn, "del", v);
        },
        "buy": () => openBuy(true),
    };

    const act = {
        "pick": (v) => add_pick(v, umd.cur, umd, () => openInfo(true)),
        "add": (v, h) => {
            umd.startWait();

            uDb(null, "code/gen",
                {
                    line: cline(),
                    rule: "oil",
                },
                r => {
                    v["sn"] = r.psn;
                    umd.update("oil/add", { v: v }, h);

                    stock_log("lgoil", r.psn, "in", v);
                },
                e=> umd.setErr());
        },
        "edit": (v, h) => {
            umd.update("oil/mditem", { v: v }, h);

            stock_log("lgoil", v.sn, "md", v);
        },
        "buy": (v) => {
            umd.startWait();

            uJob(null, "sale/order",
                {
                    line: cline(),
                    v: v,
                },
                r => {
                    umd.endWait();
                    openInfo(true);
                },
                e => umd.setErr());
        }
    };

    const getCol = useMemo(() => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 170, formatter: (props) => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "pick")} disabled={no_acc("uac")}>{loc("l_741")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(null, d, "edit")} disabled={no_acc("uab")}>{loc("l_235")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "del")} disabled={no_acc("uab")}>{loc("l_237")}</BtTxt>
                    </div>
                );
            }},
        ];

        get_col(tmp, col, map_supply, map_custom);

        return tmp;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [col]);

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];

        col.forEach(d => {
            if (d.sn === "custom") {
                d.ctl = custom;
            } else if (d.sn === "unit") {
                d.ctp = "auto";
            } else if (d.sn === "supply") {
                d.ctp = "list";
                d.ctl = supply;
            }

            ret.push(d);
        });

        return ret;
    };

    const hreturn = () => {
        load_col(setCol);
        umd.hreturn();
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: "oiltask", name: loc("l_113")},
        ];

        return <ColView hreturn={hreturn} title={loc("l_113")} subtitle={loc("l_221")} list={list} cur="oiltask"/>;
    }

    if (umd.isFin("census")) {
        return <Census hreturn={() => umd.hreturn()} map_custom={map_custom} data={umd.value}/>;
    }

    if (umd.isFin("add") || umd.isFin("edit")) {
        return <HandView umd={umd} title={loc("l_113")} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={() => umd.pact(pact, null, "buy")} disabled={no_acc("uab")}>{loc("l_552")}</Btn>
            <Btn className="mx-4" color="green" hcmd={() => umd.pact(null, null, "add")} disabled={no_acc("uab")}>{loc("l_239")}</Btn>
            <Btn hcmd={() => umd.pact(null, null, "col")} disabled={no_acc("uab")}>{loc("l_221")}</Btn>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            {loc("l_113")}
            <Btn className="ml-8" hcmd={() => umd.pact(null, null, "census")} color="teal">{loc("l_115")}</Btn>
        </div>
    );

    const getMsg = () => {
        if (umd.isFin("pick")) {
            return loc("l_754");
        }

        return loc("l_562");
    };

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable col={getCol} row={getRow} high={high}/>
            <DlgBuy open={open_buy} setOpen={openBuy} hcmd={(v) => umd.act(act, v)} custom={custom} map_custom={map_custom}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={getMsg()}/>
            <DlgVal open={open_val} hcmd={v => umd.act(act, v)} setOpen={openVal} data={umd.cur} map_custom={map_custom}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {TaskView};
